<script setup lang="ts">
import { ElDialog, ElMessage, ElScrollbar } from 'element-plus'
import { propTypes } from '@/utils/propTypes'
import { computed, useAttrs, reactive, onMounted, onUpdated, ref } from 'vue'
import { Paging } from '@/config/public'
import { useI18n } from '@/hooks/web/useI18n'
import { selectRefEntity } from '@/api/develop/form'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { useAppStore } from '@/store/modules/app'

const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
const appStore = useAppStore()
const { t } = useI18n()
const refTable = ref()

defineOptions({
  name: 'GeneralSelectDialog'
})

const emit = defineEmits(['selected', 'cancel'])

const props = defineProps({
  modelValue: propTypes.bool.def(false),
  colId: propTypes.string,
  sortField: propTypes.string.def(''),
  sortOrder: propTypes.string.def(''),
  noDeleted: propTypes.bool.def(false),
  lastValue: propTypes.string,
  title: propTypes.string.def('')
})

const state = reactive({
  searchKey: '',
  // 表格數據
  tableView: [{} as any],
  // 分頁相關屬性
  totalCount: 0,
  pageSizes: Paging.sizes,
  queryBody: {
    key: '',
    pageNo: 1,
    pageSize: 10,
    sortField: '',
    sortOrder: '',
    lang: curLang,
    colId: '',
    noDeleted: false
  },
  languageInfo: {} as any,
  colInfo: [{} as any],
  curSelect: {} as any
})

//对话属性值变化时查询后端数据
onUpdated(() => {
  //显示状态下才查询
  if (!props.modelValue) {
    return
  }
  handleSearch()
})

onMounted(() => {})

const changePage = (page) => {
  state.queryBody.pageNo = page
  handleSearch()
}
const changePageSize = (pageSize) => {
  state.queryBody.pageSize = pageSize
  state.queryBody.pageNo = 1
  handleSearch()
}

//重置查询
const resetSearch = () => {
  state.searchKey = ''
  handleSearch()
}

//查询分页记录
const handleSearch = async () => {
  appStore.setFooter(false)
  state.queryBody.noDeleted = props.noDeleted
  state.queryBody.colId = props.colId
  state.queryBody.sortField = props.sortField
  state.queryBody.sortOrder = props.sortOrder
  state.queryBody.key = state.searchKey
  state.tableView = []
  await selectRefEntity(state.queryBody)
    .then((res) => {
      const result = res as any

      state.tableView = result.result.data
      state.totalCount = result.result.totalCount
      state.languageInfo = result.data.languageInfo
      state.colInfo = result.data.colInfo
      setSeletedVaue()
    })
    .catch(() => {})
}

//处理上次选中的值
const setSeletedVaue = () => {
  const lastValue = props.lastValue
  if (!lastValue) {
    return
  }
  if (!state.tableView || state.tableView.length == 0) {
    return
  }
  for (const row of state.tableView) {
    if (row.id == lastValue) {
      refTable.value.setCurrentRow(row)
    }
  }
}

const getBindValue = computed(() => {
  const delArr: string[] = ['title', 'noDeleted', 'colId', 'sortField', 'sortOrder', 'lastValue']
  const attrs = useAttrs()
  const obj = { ...attrs, ...props }
  for (const key in obj) {
    if (delArr.indexOf(key) !== -1) {
      delete obj[key]
    }
  }
  return obj
})

//选择行变化
const changeRow = (currentRow) => {
  if (currentRow) {
    state.curSelect = currentRow
  } else {
    state.curSelect = null
  }
}

//双击行,直接选中
const dblclickRow = (row) => {
  if (row) {
    state.curSelect = row
    clickOK()
  } else {
    state.curSelect = null
  }
}

//确定按钮事件
const clickOK = () => {
  if (!state.curSelect) {
    ElMessage.warning(t('common.selectOne'))
    return
  }
  emit('selected', state.curSelect)
}
//取消按钮事件
const clickCancel = () => {
  emit('cancel')
}
</script>

<template>
  <ElDialog
    v-bind="getBindValue"
    lock-scroll
    draggable
    :fullscreen="false"
    :close-on-click-modal="false"
  >
    <template #title>
      <div class="flex justify-between">
        <slot name="title">
          <span style="font-weight: bold; font-size: 14px; color: #666">
            {{ state.languageInfo.entName + ' - ' + $t('dialog.fastPick') }}
          </span>
        </slot>
      </div>
    </template>
    <ElScrollbar style="margin: -18px -8px">
      <div>
        <!-- 搜索條件卡片 -->
        <el-card>
          <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
            <el-col :sm="5" :md="4" style="text-align: right; font-size: 12px">{{
              $t('common.searchKey')
            }}</el-col>
            <el-col :sm="19" :md="12" style="text-align: left">
              <el-input v-model="state.searchKey" @keyup.enter="handleSearch" />
            </el-col>
            <el-col :sm="24" :md="8" style="text-align: right">
              <div style="margin-right: -5px">
                <el-button @click="handleSearch" type="primary" size="small" plain
                  ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span>
                </el-button>
                <el-button @click="resetSearch" type="info" size="small" plain>
                  <Icon icon="icon-park-solid:clear-format" /><span>{{ $t('common.reset') }}</span>
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-card>
        <el-container class="mainArea">
          <el-main class="formcard">
            <!-- 搜索結果表格 -->
            <el-table
              ref="refTable"
              :data="state.tableView"
              tooltip-effect="light"
              style="width: 100%; border: 1px solid #ddd; font-size: 12px"
              row-key="id"
              default-expand-all
              highlight-current-row
              @current-change="changeRow"
              @row-dblclick="dblclickRow"
              :header-cell-style="{
                background: 'var(--el-color-primary-light-9)',
                color: '#409eff'
              }"
            >
              <el-table-column
                v-for="col in state.colInfo"
                :key="col.fieldName"
                :prop="col.fieldName"
                :label="state.languageInfo[col.fieldName]"
                show-overflow-tooltip
                min-width="120"
                v-show="col.fieldName != 'id'"
              />
            </el-table>
            <!-- 分頁器 -->
            <div class="demo-pagination-block"
              ><el-pagination
                v-model:currentPage="state.queryBody.pageNo"
                v-model:page-size="state.queryBody.pageSize"
                @current-change="changePage"
                @size-change="changePageSize"
                :page-sizes="state.pageSizes"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="state.totalCount"
                style="font-size: 12px !important"
            /></div>
          </el-main>
        </el-container>
      </div>
    </ElScrollbar>
    <template #footer>
      <el-button @click="clickCancel">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="clickOK">{{ $t('common.ok') }}</el-button>
    </template>
  </ElDialog>
</template>

<style lang="less" scoped>
.@{elNamespace}-dialog__header {
  border-bottom: 1px solid var(--tags-view-border-color);
}

.@{elNamespace}-dialog__footer {
  border-top: 1px solid var(--tags-view-border-color);
}

.is-hover {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

:deep(.el-select .el-option .el-input .el-select-dropdown__item) {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
  font-size: 12px;
}

:deep(.el-dialog__body) {
  padding: 10px 50px;
}
:deep(.v-footer) {
  height: 0px;
}
.mainArea {
  overflow-x: hidden;
  height: 420px;
}
.formcard {
  margin: -12px -19px 0 -20px;
}
// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(span.el-pagination__jump) {
  font-size: 12px;
}
:deep(span.el-pagination__total) {
  font-size: 12px;
}
:deep(.btn-next) {
  height: 28px;
}
:deep(.el-pagination button) {
  height: 28px;
}
</style>
